#pragma once

#include <iostream>
#include <cassert>
#include <functional>
#include <sys/epoll.h>
#include <unordered_map>
#include "Log.hpp"
#include "Err.hpp"
#include "Epoller.hpp"
#include "Sock.hpp"
#include "Util.hpp"
#include "Protocol.hpp"

namespace tcpserver
{
    class tcpServer;
    class Connection;

    static const uint16_t defaultport = 8080;
    static const int num = 64;

    typedef std::function<void(Connection *)> func_t;
    class Connection
    {
    public:
        Connection(int sock, tcpServer *tsp)
            : _sock(sock), _tsp(tsp)
        {
        }
        ~Connection()
        {
        }

    public:
        void Register(func_t recver, func_t sender, func_t excepter)
        {
            _recver = recver;
            _sender = sender;
            _excepter = excepter;
        }

        void Close()
        {
            if (_sock > 0)
                close(_sock);
        }

    public:
        int _sock;

        std::string _inbuffer;  // 输入缓冲区
        std::string _outbuffer; // 输入出缓冲区

        func_t _recver;   // 从sock_读
        func_t _sender;   // 向sock_写
        func_t _excepter; // 处理sock_ IO的时候上面的异常事件

        tcpServer *_tsp;
    };

    class tcpServer
    {
    public:
        tcpServer(const func_t &func, const uint16_t &port = defaultport)
            : _service(func), _port(port), _revs(nullptr)
        {
        }
        ~tcpServer()
        {
            _sock.Close();
            _epoller.Close();
            if (nullptr == _revs)
                delete[] _revs;
        }

    private:
        void Recver(Connection *conn)
        {
            char buffer[1024];
            while (true)
            {
                ssize_t s = recv(conn->_sock, buffer, sizeof(buffer) - 1, 0);
                if (s > 0)
                {
                    buffer[s] = 0;
                    conn->_inbuffer += buffer;
                    logMessage(DEBUG, "\n%s", conn->_inbuffer.c_str());
                    _service(conn);
                }
                else if (s == 0)
                {
                    if (conn->_excepter)
                    {
                        conn->_excepter(conn);
                        return;
                    }
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->_excepter)
                        {
                            conn->_excepter(conn);
                            return;
                        }
                    }
                }
            }
        }
        void Sender(Connection *conn)
        {
            while (true)
            {
                ssize_t s = send(conn->_sock, conn->_outbuffer.c_str(), conn->_outbuffer.size(), 0);
                if (s > 0)
                {
                    if (conn->_outbuffer.empty())
                        break;
                    else
                        conn->_outbuffer.erase(0, s);
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->_excepter)
                        {
                            conn->_excepter(conn);
                            return;
                        }
                    }
                }
            }
            // 如果没有发送完毕，需要对对应的sock开启对写事件的关心， 如果发完了，我们要关闭对写事件的关心！
            if (!conn->_outbuffer.empty())
                conn->_tsp->EnableReadWrite(conn, true, true);
            else
                conn->_tsp->EnableReadWrite(conn, true, false);
        }

        void Excepter(Connection *conn)
        {
            logMessage(DEBUG, "Excepter begin");

            _epoller.Control(conn->_sock, 0, EPOLL_CTL_DEL);
            conn->Close();
            _connections.erase(conn->_sock);

            logMessage(DEBUG, "关闭%d 文件描述符的所有的资源", conn->_sock);

            delete conn;
        }

        void Accepter(Connection *conn)
        {
            for (;;)
            {
                std::string clientip;
                uint16_t clientport;
                int err = 0;
                int sock = _sock.Accept(&clientip, &clientport, &err);
                if (sock > 0)
                {
                    AddConnection(sock, EPOLLIN | EPOLLET,
                                  std::bind(&tcpServer::Recver, this, std::placeholders::_1),
                                  std::bind(&tcpServer::Sender, this, std::placeholders::_1),
                                  std::bind(&tcpServer::Excepter, this, std::placeholders::_1));

                    logMessage(DEBUG, "get a new link, info:[%s:%d]", clientip.c_str(), clientport);
                }
                else
                {
                    if (err == EAGAIN || err == EWOULDBLOCK)
                        break;
                    else if (err == EINTR)
                        continue;
                    else
                        break;
                }
            }
        }
        void AddConnection(int sock, uint32_t events, func_t recver, func_t sender, func_t excepter)
        {
            // 1. 首先要为该sock创建Connection，并初始化，并添加到_connections
            if (sock & EPOLLIN)
                Util::SetNonBlock(sock);

            Connection *conn = new Connection(sock, this);
            // 2. 给对应的sock设置对应回调处理方法
            conn->Register(recver, sender, excepter);

            // 3. 其次将sock与它要关心的事件"写透式"注册到epoll中，让epoll帮我们关心
            bool r = _epoller.AddEvent(sock, events);
            assert(r);
            (void)r;

            // 4. 将kv添加到_connections
            _connections.insert(std::make_pair(sock, conn));
            logMessage(DEBUG, "add new sock : %d in epoll and unordered_map", sock);
        }

        bool IsConnectionExists(int sock)
        {
            auto pos = _connections.find(sock);
            return pos != _connections.end();
        }

        void Loop(int timeout)
        {
            // 获取已经就绪的事件
            int n = _epoller.Wait(_revs, _num, timeout);
            for (int i = 0; i < n; i++)
            {
                int sock = _revs[i].data.fd;
                uint32_t events = _revs[i].events;

                // 将所有的异常问题，全部转化 成为读写问题
                if (events & EPOLLERR)
                    events |= (EPOLLIN | EPOLLOUT);
                if (events & EPOLLHUP)
                    events |= (EPOLLIN & EPOLLOUT);
                if ((events & EPOLLIN) && (IsConnectionExists(sock) && _connections[sock]->_recver))
                    _connections[sock]->_recver(_connections[sock]);
                if ((events & EPOLLOUT) && (IsConnectionExists(sock) && _connections[sock]->_sender))
                    _connections[sock]->_sender(_connections[sock]);
            }
        }

    public:
        void initServer()
        {
            // 1. 创建socket
            _sock.Socket();
            _sock.Bind(_port);
            _sock.Listen();

            // 2. 构建Epoll
            _epoller.Create();

            // 3. 将目前唯一的一个sock，添加到epoller中， 之前需要先将对应的fd设置成为非阻塞
            // listensock_也是一个socket啊，也要看做成为一个Connection
            AddConnection(_sock.Fd(), EPOLLIN | EPOLLET, std::bind(&tcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);
            _revs = new struct epoll_event[num];
            _num = num;
        }

        void EnableReadWrite(Connection *conn, bool readable, bool writeable)
        {
            uint32_t event = (readable ? EPOLLIN : 0) | (writeable ? EPOLLOUT : 0) | EPOLLET;
            _epoller.Control(conn->_sock, event, EPOLL_CTL_MOD);
        }

        void Dispatcher()
        {
            int timeout = 1000;
            while (true)
            {
                Loop(timeout);
            }
        }

    private:
        uint16_t _port;
        Sock _sock;
        Epoller _epoller;
        std::unordered_map<int, Connection *> _connections;
        struct epoll_event *_revs;
        int _num;
        func_t _service;
    };
}